<template>
  <div class="bg-light min-vh-100 d-flex flex-column">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link :to="`/english/weekTestExam?noticeId=${noticeId}&examPaperId=${examPaperId}`" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">小作文</h5>
    </div>

    <!-- 写作任务卡片 -->
    <div class="writing-card flex-grow-1">
      <div class="task-info mb-3">
        <h6 class="mb-2">{{ subjectName }}&nbsp;&nbsp;小作文题目</h6>
        <p class="text-muted">
          {{article}}
        </p>
      </div>

      <!-- 写作区域 -->
      <div class="writing-area">
        <textarea
          v-model="userAnswer"
          class="form-control"
          rows="10"
          placeholder="在此输入你的答案..."
        ></textarea>
        <div class="word-count text-end mt-2">
          字数：{{ wordCount }} / 100
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <div class="action-buttons">
        <button class="btn btn-primary" @click="submitAnswers">
          提交答案
        </button>
      </div>
    </div>

    <!-- 范文弹窗 -->
    <div class="modal fade" id="sampleAnswerModal" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">参考范文</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <p>Dear Professor Smith,</p>
            <p>I am writing to request permission to visit your laboratory. I am a graduate student from China, majoring in Computer Science at XYZ University. I have read many of your published papers and am deeply impressed by your research in artificial intelligence.</p>
            <p>I will be in your city next month and would greatly appreciate the opportunity to visit your lab and possibly discuss your current research projects. I am particularly interested in your work on machine learning algorithms.</p>
            <p>Thank you for your consideration.</p>
            <p>Best regards,<br>Li Ming</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Modal } from 'bootstrap'
import {moduleTypeDict, paperTypeDict} from "@/router/dict";
import http from "@/router/http";
import router from "@/router/index";

export default {
  name: 'SmallWritingView',
  data() {
    return {
      userAnswer: '',
      noticeId: null,
      modal: null,
      selectYear: null,
      startTime: 0, // 记录答题开始时间（毫秒数）
      totalTimeSpent: 0, // 累计答题时间（毫秒数）
      subjectName: '',
      article: '',
      examPaperId: '',
      questionId: '',
      userAnswers: []
    }
  },
  computed: {
    wordCount() {
      return this.userAnswer.trim().split(/\s+/).length
    }
  },
  mounted() {
    // 使用导入的 Modal
    this.modal = new Modal(document.getElementById('sampleAnswerModal'))
    this.noticeId = this.$route.query.noticeId;
    this.examPaperId = this.$route.query.examPaperId;
    this.startTime = Date.now(); // 记录答题开始时间（毫秒数）
    this.fetchDataFromBackend();
  },
  methods: {
    showSampleAnswer() {
      this.modal.show()
    },
    async fetchDataFromBackend() {
      try {
        const moduleType = moduleTypeDict.find(item => item.code === 'xzw').name;
        const params = {
          examPaperId: this.examPaperId,
          subjectName: 'english',
          moduleType: moduleType,
          currentQuestionIndex: 1
        }
        const response = await http.get('/student/question/getQuestionInfoForEnglish', {params: params});
        const data = response.data;
        if (data && data.code === 1 && data.response) {
          this.examPaperId = data.response.examPaperId;
          this.questionId = data.response.questionId;
          this.article = data.response.article;
          this.subjectName = data.response.subjectName;
        } else {
          alert("暂无数据，请稍后再试");
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
        }
      } catch (error) {
        console.error('获取阅读数据失败:', error);
      }
    },
    async submitAnswers() {
      try {
        const currentTime = Date.now(); // 获取当前时间（毫秒数）
        this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
        this.userAnswers.push({
          index: 0,
          value: this.userAnswer.trim(),
        })
        const submitParentData = {
          questionId: this.questionId,
          examPaperId: this.examPaperId,
          totalTimeSpent: this.totalTimeSpent,
          resource: 1,
          userAnswer: this.userAnswers,
          isTest: true
        }
        // 发送POST请求将答题数据提交到后端
        const response = await http.post('/student/answer/submitAnswerForEnglish', submitParentData);
        if (response.status === 200) {
          alert('答题数据提交成功');
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
          // 可以根据业务需求进行其他操作，比如提示用户提交成功，跳转到特定页面等
        } else {
          console.error('答题数据提交失败');
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
          // 同样可根据业务需求进行相应提示等操作
        }
      } catch (error) {
        console.error('提交答题数据出现错误:', error);
      }
    }
  }
}
</script>

<style scoped>
.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.writing-card {
  background: white;
  margin: 15px;
  margin-bottom: 80px; /* 为底部按钮留出空间 */
  padding: 20px;
  border-radius: 15px;
  overflow-y: auto;
}

.task-info {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.writing-area textarea {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  font-size: 16px;
  resize: none;
}

.word-count {
  color: #666;
  font-size: 14px;
}

.bottom-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}
</style> 